using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Media; 

using FarseerGames.FarseerPhysics;
using FarseerGames.FarseerPhysics.Dynamics.Joints;
using FarseerGames.FarseerPhysics.Dynamics.Springs;
using FarseerGames.FarseerPhysics.Controllers;
using FarseerGames.FarseerPhysics.Factories;
using FarseerGames.FarseerPhysics.Mathematics;
using FarseerGames.FarseerPhysics.Interfaces;
using FarseerGames.FarseerPhysics.Collisions;

using Common;
using System.Timers;
using FarseerGames.FarseerPhysics.Dynamics;

namespace Matryoshka
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        PhysicsSimulatorView psView;
        PhysicsSimulator physicsSimulator = new PhysicsSimulator(new Vector2(0, 4000));
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        InputHelper input;
        Camera2D camera;
        
        Contraption level01 = new Contraption();
        Contraption level01foreground = new Contraption();

        Song songDemoSolnyshko;
        SoundEffect soundBop;

        SpriteFont font;

        Doll dollRed = new Doll();
        Doll dollBlue = new Doll();

        Body bodyCamera;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            // TCC: Load the textures in the texture manager
            TextureManager.LoadContent(Content);
            
            // TCC: Load the spritefonts into the font manager
            FontManager.LoadContent(Content);

            // TCC: Load the level via the contraption class
            level01.Build("level01.xml", physicsSimulator, Content);
            level01foreground.Build("level01foreground.xml", physicsSimulator, Content);
            level01.mapGeom["g_ground"].Tag = new GeomInfo(GeomType.Ground, null);
            foreach (Geom geom in level01.mapBlockGeoms.Values)
            {
                geom.Tag = new GeomInfo(GeomType.Ground, null);
            }


            Random random = new Random();
            int dollFace = random.Next(5) + 1;
            dollRed.LoadContent("Red", "0" + dollFace.ToString(), physicsSimulator, Content);
            dollRed.CurrentDollState.Body.Position += new Vector2(-500f, 0);
            dollRed.keyHopLeft = Keys.A;
            dollRed.keyHopRight = Keys.D;
            dollRed.keyJump = Keys.W;
            dollRed.keyStomp = Keys.S;
            dollRed.keyShead = Keys.E;

            dollBlue.LoadContent("Blue", "0" + dollFace.ToString(), physicsSimulator, Content);
            dollBlue.CurrentDollState.Body.Position += new Vector2(500f, 0);

            bodyCamera = BodyFactory.Instance.CreateBody(physicsSimulator, 1f, 1f);
            bodyCamera.IgnoreGravity = true;
            camera = new Camera2D(new Vector2(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height));
            camera.TrackingBody = bodyCamera;
            camera.Zoom = .5f;

            input = new InputHelper();

            songDemoSolnyshko = Content.Load<Song>("Music/demo-solnyshko");
            MediaPlayer.Play(songDemoSolnyshko);

            soundBop = Content.Load<SoundEffect>("Sounds/squeez");

            font = Content.Load<SpriteFont>("Fonts/Hud");

            psView = new PhysicsSimulatorView(physicsSimulator);
            psView.LoadContent(GraphicsDevice, Content);
        }


        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        private void UpdateCamera()
        {
            Vector2 p1 = dollBlue.Body.Position;
            Vector2 p2 = dollRed.Body.Position;

            bodyCamera.Position = new Vector2( (p1.X + p2.X) / 2, (p1.Y + p2.Y) / 2);
            
            float distance = (float)Math.Sqrt( Math.Pow((p1.X - p2.X), 2) + Math.Pow((p1.Y - p2.Y),2));

            camera.Zoom = (1 / (distance* .002f));

            if (camera.Zoom < .1f)
            {
                camera.Zoom = .1f;
            }

            if (camera.Zoom > .5f)
            {
                camera.Zoom = .5f;
            }
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            float dtime = gameTime.ElapsedGameTime.Milliseconds * 0.001f;

            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            dollRed.HandleInput(input);
            dollBlue.HandleInput(input);

            dollRed.Update();
            dollBlue.Update();

            DecalManager.Update(dtime);
            UpdateCamera();

            // TODO: Add your update logic here
            physicsSimulator.Update(dtime);
            camera.Update(input);
            input.Update();
            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code 
            spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.None, camera.CameraMatrix);

            level01.Draw(spriteBatch);

            dollBlue.Draw(spriteBatch);
            dollRed.Draw(spriteBatch);

            level01foreground.Draw(spriteBatch);

            //psView.Draw(spriteBatch);
            DecalManager.Draw(spriteBatch);

            spriteBatch.End();

            spriteBatch.Begin();
            spriteBatch.DrawString(font, "Player 1:  " + dollRed.Score.ToString(), Vector2.Zero, Color.Yellow);
            spriteBatch.DrawString(font, "Player 2:  " + dollBlue.Score.ToString(), new Vector2(0, 32), Color.Yellow);
            spriteBatch.End();


            base.Draw(gameTime);
        }
    }
}
